package com.aj.controller;

import com.aj.Interface.UserService;
import com.aj.pojo.Permission;
import com.aj.pojo.Role;
import com.aj.pojo.User;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Controller("springSecurityUserService")
public class springSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.findByUsername(username);
        if (user==null){
            return  null;
        }
        List<GrantedAuthority> grantedAuthoritylist = new ArrayList<GrantedAuthority>();

        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                String keyword = permission.getKeyword();
                grantedAuthoritylist.add(new SimpleGrantedAuthority(keyword));
            }
        }
        System.out.println(grantedAuthoritylist.size());
        org.springframework.security.core.userdetails.User userDetails = new org.springframework.security.core.userdetails.User
                (username,user.getPassword(),grantedAuthoritylist);


        return userDetails;
    }
}
